<template>
  <div>
    <el-tabs v-model="qualityTabType" class="demo-tabs" @tab-change="qualityTabChange">
      <el-tab-pane label="未质检" name="0">
        <el-row :gutter="10" class="mb8" style="float:left">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd">新建表单</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Delete" @click="handleDelete">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Upload" @click="handleImport">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <el-col :span="1.5" v-if="isNeedQuality(route.query.curKey)">
            <el-button type="primary" icon="EditPen" @click="handleQualityTesting">提交质检</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Setting" @click="handleColumn">列设置</el-button>
          </el-col>
        </el-row>
        <el-table v-loading="tableLoading" :data="tableData" :border="true" @selection-change="tableChange" stripe
          v-if="columnDataChecked.length > 0">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column v-for="(item, index) in columnDataChecked" :key="item.fieldName" :label="item.name"
            :prop="item.fieldName" align="center" :min-width="minWidthSet(item.name)">
            <template #default="{ row }" v-if="index == '0'">
              <el-link :underline="false" type="primary" @click="getFormDetail(row)">{{ row[item.fieldName]
              }}</el-link>
            </template>
            <template #default="{ row }" v-if="checkDict(item.fieldName, route.query.curKey)">
              <dict-tag :value="row[item.fieldName]" :code="checkDict(item.fieldName, route.query.curKey)"></dict-tag>
            </template>
          </el-table-column>
        </el-table>

        <pagination style="margin-top: 15px" v-show="total > 0" :total="total" v-model:page="queryParams.page"
          v-model:limit="queryParams.rows" @pagination="getList" />
      </el-tab-pane>
      <el-tab-pane label="质检不通过" name="2">
        <el-row :gutter="10" class="mb8" style="float:left">
          <el-col :span="1.5">
            <el-button type="primary" icon="Delete" @click="handleDelete">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <el-col :span="1.5" v-if="isNeedQuality(route.query.curKey)">
            <el-button type="primary" icon="EditPen" @click="handleQualityTesting">提交质检</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Setting" @click="handleColumn">列设置</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="tableLoading" :data="tableData" :border="true" @selection-change="tableChange" stripe
          v-if="columnDataChecked.length > 0">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column v-for="(item, index) in columnDataChecked" :key="item.fieldName" :label="item.name"
            :prop="item.fieldName" align="center" :min-width="minWidthSet(item.name)">
            <template #default="{ row }" v-if="index == '0'">
              <el-link :underline="false" type="primary" @click="getFormDetail(row)">{{ row[item.fieldName]
              }}</el-link>
            </template>
            <template #default="{ row }" v-if="checkDict(item.fieldName, route.query.curKey)">
              <dict-tag :value="row[item.fieldName]" :code="checkDict(item.fieldName, route.query.curKey)"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="{ row }">
              <!-- <el-button type="text">查看理由</el-button>
              <el-button type="text" @click="handleQualityTesting">提交质检</el-button> -->
              <el-link type="primary" :underline="false" @click="viewQuality(row)">查看理由</el-link>
              <el-link type="primary" :underline="false" @click="quality(row[idName])">提交质检</el-link>
            </template>
          </el-table-column>
        </el-table>

        <pagination style="margin-top: 15px" v-show="total > 0" :total="total" v-model:page="queryParams.page"
          v-model:limit="queryParams.rows" @pagination="getList" />
      </el-tab-pane>
      <el-tab-pane label="质检通过" name="3">
        <el-row :gutter="10" class="mb8" style="float:left">
          <el-col :span="1.5">
            <el-button type="primary" icon="Delete" @click="handleDelete">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Setting" @click="handleColumn">列设置</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="tableLoading" :data="tableData" :border="true" @selection-change="tableChange" stripe
          v-if="columnDataChecked.length > 0">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column v-for="(item, index) in columnDataChecked" :key="item.fieldName" :label="item.name"
            :prop="item.fieldName" align="center" :min-width="minWidthSet(item.name)">
            <template #default="{ row }" v-if="index == '0'">
              <el-link :underline="false" type="primary" @click="getFormDetail(row)">{{ row[item.fieldName]
              }}</el-link>
            </template>
            <template #default="{ row }" v-if="checkDict(item.fieldName, route.query.curKey)">
              <dict-tag :value="row[item.fieldName]" :code="checkDict(item.fieldName, route.query.curKey)"></dict-tag>
            </template>
          </el-table-column>
        </el-table>

        <pagination style="margin-top: 15px" v-show="total > 0" :total="total" v-model:page="queryParams.page"
          v-model:limit="queryParams.rows" @pagination="getList" />
      </el-tab-pane>
    </el-tabs>

    <ExcelImport v-model:open="upload.open" :uploadParams="upload" @importSuccess="importSuccess"></ExcelImport>
    <ColumnSetting ref="columnRef" v-model:open="columnSetting.open" :title="columnSetting.title" :columnData="columnData"
      @saveColumn="saveColumn"></ColumnSetting>
    <Quality v-model:open="qualityOpen" :data="qualityData" />
  </div>
</template>
<script setup>
import { getAll, deleteList, getField, fieldOption, submit } from '@/api/businessManage/dataLoader/otherData'
import ExcelImport from '@/components/ExcelImport'
import ColumnSetting from '@/components/ColumnSetting'
import { treeData } from '@/views/businessManage/common/propertyTree'
import { checkDict } from '@/views/businessManage/common/dict'
import { minWidthSet } from '@/views/businessManage/common/minWidth'
import { isNeedQuality } from '@/views/businessManage/common/intergrateTree'
import Quality from '@/views/businessManage/common/quality'

const router = useRouter()
const route = useRoute()
const subjectId = route.query.id
const { proxy } = getCurrentInstance()

let baseUrl
let formName
let idName
const upload = reactive({
  open: false,
  url: `${baseUrl}/dataImport`,
  templateName: `${formName}-属性表.xls`,
  params: { smId: subjectId }
})
const columnSetting = reactive({
  open: false,
  title: formName
})
watch(() => route.query.curKey, () => {
  treeData.map(item => {
    let compareValue
    if (route.query.curKey) {
      compareValue = route.query.curKey
    } else {
      compareValue = route.name
    }
    let objItem = item.children.find(itemChil => itemChil.pathName == compareValue)
    if (objItem) {
      baseUrl = objItem.baseUrl
      formName = objItem.label
      idName = objItem.idName
    }
  })
  upload.templateName = `${formName}-属性表.xls`
  upload.url = `${baseUrl}/dataImport`
  columnSetting.title = formName
}, { immediate: true })

const page = ref(1)
const rows = ref(10)
const total = ref(0)
const props = defineProps({
  queryParams: Object
})
const emits = defineEmits(['update:addDrawer', 'loadingChange'])
const { queryParams } = props

const qualityTabType = ref('0')
const qualityTabChange = () => {
  handQuery()
}

const handleAdd = () => {
  const { id, name, curKey } = route.query
  router.push({ path: `/businessManage/dataLoader/subject/otherData/${curKey}`, query: { id, name } })
}
const handleDelete = () => {
  if (ids.value.length == 0) {
    proxy.$modal.msgWarning('请至少选择一条数据！')
    return
  }
  proxy.$modal.confirm('是否确定删除？').then(() => {
    return deleteList(baseUrl, ids.value)
  }).then(() => {
    proxy.$modal.msgSuccess('删除成功！')
    handQuery()
  })
}
const handleImport = () => {
  upload.open = true
}
const handleExport = () => {
  if (ids.value.length == 0) {
    proxy.$modal.msgWarning('请至少选择一条数据！')
    return
  }
  proxy.download(`${baseUrl}/dataExport/${ids.value}`, {}, `${formName}${new Date().getTime()}.xls`)
}
const handleQualityTesting = () => {
  if (ids.value.length == 0) {
    proxy.$modal.msgWarning('请至少选择一条数据！')
    return
  }
  quality(ids.value)
}
// 查看理由
const qualityOpen = ref(false)
const qualityData = ref({})
const viewQuality = (row) => {
  qualityOpen.value = true
  qualityData.value = row
}
const quality = (ids) => {
  submit(baseUrl, ids).then(res => {
    proxy.$modal.msgSuccess('提交质检成功！')
    queryList()
  })
}
const handleColumn = () => {
  columnSetting.open = true
}

const qualifiedData = reactive({
  tableLoading: false,
  tableData: []
})
const { tableLoading, tableData } = toRefs(qualifiedData)

const ids = ref([])
const tableChange = (val) => {
  ids.value = val.map(item => item[idName])
}
const columnData = ref([])
const columnDataChecked = ref([])
const handQuery = () => {
  getField(baseUrl).then(res => {
    columnData.value = res.data
    columnDataChecked.value = res.data.filter(item => item.status == '1')
    getList()
  })
}
const getList = () => {
  tableLoading.value = true
  getAll(baseUrl, { ...queryParams, page: page.value, rows: rows.value, smId: subjectId, qcFlag: qualityTabType.value }).then(res => {
    tableData.value = res.data.rows
    total.value = res.data.total
    tableLoading.value = false
    emits('loadingChange')
  })
}

const importSuccess = () => {
  page.value = 1
  handQuery()
}
const saveColumn = (data) => {
  fieldOption(baseUrl, data).then(res => {
    proxy.$modal.msgSuccess('保存成功！')
    columnSetting.open = false
    handQuery()
  })
}

const getFormDetail = (row) => {
  const { id, name, curKey } = route.query
  router.push({ path: `/businessManage/dataLoader/subject/otherData/${curKey}`, query: { id, name, detailId: row[idName] } })
}

defineExpose({
  page,
  rows,
  handQuery
})
</script>